package com.crissy.messageService.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.crissy.messageService.common.Result;
import com.crissy.messageService.entity.Message;
import com.crissy.messageService.mapper.MessageMapper;
import com.crissy.messageService.service.IMessageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crissy.messageService.utils.AESUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Crissy-月下闲人
 * @since 2024-03-29
 */
@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    @Resource
    private MessageMapper messageMapper;
    @Value("${crissy.secret_key}")
    private String secretKey;

    /**
     * 提交信息的方法，首先对传入的消息对象进行AES加密处理，然后将加密后的信息存储到数据库中。
     *
     * @param message  包含用户信息的消息对象，这些信息将被加密并存储。
     * @param message1 包含相同用户信息但用途不同的消息对象，用途可能涉及展示等。
     * @return Result<String> 提交成功返回成功信息，失败返回失败信息。
     */
    @Override
    public Result<String> toSubmit(Message message, Message message1) {
//        try {
//            // 对message中的敏感信息进行AES加密
//            message.setName(AESUtils.encrypt(secretKey, message.getName()));
//            message.setEmail(AESUtils.encrypt(secretKey, message.getEmail()));
//            message.setIdNumber(AESUtils.encrypt(secretKey, message.getIdNumber()));
//            message.setPhone(AESUtils.encrypt(secretKey, message.getPhone()));
//            message.setAddress(AESUtils.encrypt(secretKey, message.getAddress()));
//            message.setSex(AESUtils.encrypt(secretKey, message.getSex()));
//            message.setAge(AESUtils.encrypt(secretKey, message.getAge()));
//        } catch (Exception e) {
//            // 加密过程出错抛出运行时异常
//            throw new RuntimeException(e);
//        }

        // 将加密后的信息插入到数据库
        int insert = messageMapper.insert(message);
//        message1.setId(message.getId()); // 为message1设置id，表明它们关联
//        int insert1 = messageMapper.insertShowMessgae(message1);

        // 根据插入结果返回成功或失败的信息
        if (insert == 1) {
            return Result.success("提交成功");
        } else
            return Result.fail("提交失败");
    }


    @Override
    public Result<List<Message>> toFindByPhone(String phone) {
        return null;
    }

    @Override
    public Result<List<Message>> toFindByName(String name) {
        return null;
    }

    @Override
    public Result<List<Message>> toFindByEmail(String email) {
        return null;
    }

    @Override
    public Result<List<Message>> toFindByIdNumber(String idNumber) {
        return null;
    }

    @Override
    public Result<Message> toFindById(Long id) {
        Message message = messageMapper.selectById(id);
        if (BeanUtil.isNotEmpty(message))
            return Result.success(message);
        return Result.fail("查询失败！");
    }

    @Override
    public Result<List<Message>> toSearch(String keyword) {
        List<Message> list = messageMapper.toSearch(keyword);
        for (Message message : list) {
            dataMasking(message);
        }
        return Result.success(list);
    }

    @Override
    public Result<String> toDeleteById(Long id) {
        if (messageMapper.deleteById(id) == 1)
            return Result.success("删除成功");
        return Result.fail("删除失败");
    }


    // 数据脱敏函数
    private void dataMasking(Message message) {
        message.setName(myReplace(message.getName(), 1, message.getName().length() - 1, "*"));
        message.setPhone(myReplace(message.getPhone(), 3, message.getPhone().length() - 4, "*"));
        message.setEmail(myReplace(message.getEmail(), 3, message.getEmail().length() - 3, "*"));
        message.setIdNumber(myReplace(message.getIdNumber(), 3, message.getIdNumber().length() - 1, "*"));
        message.setAddress(myReplace(message.getAddress(), 3, message.getAddress().length() - 4, "*"));
        message.setAge((Integer.toString(RandomUtil.randomInt(0, 121))));
        message.setSex("*");
    }

    private String myReplace(String str, int left, int right, String target) {
        int len = str.length();
        if (len == 1) return str;
        if (len == 2) return str.substring(0, 1) + target;
        if (left >= len || right <= left) {
            left = 1;
            right = len - 1;
        }
        String resStr = str.substring(0, left);
        for (int i = left; i < right; i++) {
            resStr += target;
        }
        return resStr + str.substring(right);
    }
}
